package com.springboot.service.impl;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.mapper.UserMapper;
import com.springboot.model.User;
import com.springboot.service.UserService;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: TongRui乀
 * @Date: 2019-12-03 18:07
 * @description：
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insert(User user) throws Exception {

//        insert2(user);

        try {
            // 这样使用的话 异常不会影响当前方法中的事务 这个方法中的事务可以正常提交
            ((UserServiceImpl)(AopContext.currentProxy())).insert2(user);
        }catch (Exception e){
            e.printStackTrace();
        }

        this.userMapper.insert(user);

    }

    @Transactional
    @Override
    public void insertAndUpdate(User user) {


        super.save(user);

        int a = 1 / 0;

        this.userMapper.insert(user);

    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void insert2(User user) throws Exception {
        this.userMapper.insert(user);

        throw new RuntimeException("测试异常");
    }
}
